package za.org.jcicada.comms.impl.tcp;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.URI;
import java.nio.channels.SocketChannel;

import za.org.jcicada.comms.IConnection;
import za.org.jcicada.comms.IConnector;

public class TcpConnector implements IConnector {

	protected final SocketAddress target;

	public TcpConnector(String host, int port) {
		this(new InetSocketAddress(host, port));
	}

	public TcpConnector(URI locationURI) {
		this(locationURI.getHost(), locationURI.getPort());
		if (!locationURI.getScheme().equals(TcpAcceptor.TCP)) {
			throw new IllegalArgumentException(String.format("Scheme must be '%s' but was '%s'", TcpAcceptor.TCP, locationURI.getScheme()));
		}
	}
	
	public TcpConnector(SocketAddress target) {
		this.target = target;
	}

	public SocketAddress getTarget() {
		return target;
	}

	@Override
	public IConnection connect() throws IOException {
		SocketChannel socketChannel = SocketChannel.open();
		socketChannel.configureBlocking(false);
		socketChannel.connect(target);
		IConnection connection = createConnection(socketChannel);
		return connection;
	}

	protected IConnection createConnection(SocketChannel channel) throws IOException {
		return new TcpConnection(channel);
	}
	
}
